package com.zh.springcloud.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @ClassName HttpRequestUtil
 * @date: 2022.03.28 09:23
 * @Author: zhanghang
 */
@Slf4j
public class HttpRequestUtil {

	public static String getClientIp(){
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return getRemoteAddr(request);
	}

	public static String getRemoteAddr(HttpServletRequest request) {

		log.info("x-forwarded-for"+request.getHeader("x-forwarded-for"));
		log.info("x-forwarded-for"+request.getHeader("WL-Proxy-Client-IP"));
		log.info("x-forwarded-for"+request.getHeader("WL-Proxy-Client-IP"));
		log.info("x-forwarded-for"+request.getRemoteAddr());
		//
		String userName = request.getParameter("userName");
		log.info("x-forwarded-for" + userName );
		if(StringUtils.isNotBlank(userName)){
			return userName;
		}

//        log.info("x-forwarded-for"+Request.ServerVariables("Local_Addr"));
		String ip = request.getHeader("x-forwarded-for");
		if(!checkIP(ip)) {

			ip = request.getHeader("Proxy-Client-IP");

		}

		if(!checkIP(ip)) {

			ip = request.getHeader("WL-Proxy-Client-IP");

		}

		if(!checkIP(ip)) {

			ip = request.getRemoteAddr();

		}

		if (ip.contains(",")) {
			return ip.split(",")[0];
		} else {
			return ip;
		}
	}

	private static boolean checkIP(String ip) {
		if (ip == null || ip.length() == 0 || "unkown".equalsIgnoreCase(ip)
				|| ip.split("\\.").length != 4) {
			return false;
		}
		return true;
	}



	public static String getVisitorIp(HttpServletRequest request){
		// 优先取 X-Real-IP
		String ip = request.getHeader("X-Real-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("x-forwarded-for");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
			if ("0:0:0:0:0:0:0:1".equals(ip))
			{
				ip = "unknown";
			}
		}
		if ("unknown".equalsIgnoreCase(ip)){
			ip = "unknown";
			return ip;
		}
		int index = ip.indexOf(',');
		if (index >= 0){
			ip = ip.substring(0, index);
		}
		return ip;
	}
}
